package com.one.blocks.rbac.controller;

import com.one.blocks.common.response.ResponseHelper;
import com.one.blocks.common.response.WebResponse;
import com.one.blocks.rbac.controller.vo.SysLoginVo;
import com.one.blocks.security.authc.password.PasswordAuthenticationProcessingFilter;
import com.one.blocks.security.authc.password.PasswordAuthenticationToken;
import com.one.blocks.security.authc.rememberme.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-12-04 10:39:27
 */
@Api(tags = "系统登录/出接口")
@RequestMapping
@RestController
@ConditionalOnMissingBean(PasswordAuthenticationProcessingFilter.class)
public class SysLoginController implements Condition {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @ApiOperation("用户名/密码登录")
    @PostMapping("${app.blocks.security.loginUrl:/login}")
    public WebResponse<String> login(@RequestBody SysLoginVo sysLoginVo) {
        Authentication authentication = authenticationManager.authenticate(new PasswordAuthenticationToken(sysLoginVo.getUsername(), sysLoginVo.getPassword()));
        return ResponseHelper.success(tokenService.save((UserDetails) authentication.getDetails()));
    }

    @ApiOperation("登出")
    @PostMapping("${app.blocks.security.logoutUrl:/logout}")
    public WebResponse<Void> logout(HttpServletRequest request) {
        tokenService.clear(request);
        return ResponseHelper.success();
    }

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return Objects.requireNonNull(context.getBeanFactory()).containsBeanDefinition("passwordAuthenticationProcessingFilter");
    }
}
